import { _decorator, Component, Node } from 'cc';
import { NetConfig, State, WSConnectedEvent, WSRecvDataEvent } from '../../../Framework/Scripts/Managers/Net/NetCfg';
import { CocosUtils } from '../../../Framework/Scripts/Utils/CocosUtils';
import { AbNames, EventMsgKes, HallPkg, LoadingPkg } from '../Config/ResConfig';
import { ResManager } from '../../../Framework/Scripts/Managers/ResManager';
import { GameData } from '../Data/GameData';
import { decodeMsgRes, encodeMsg, Msg } from '../../AssetPackage/Props/DT';
import { ILoginReq, IloginRes } from './LoginPro';
import { UIComponent } from '../../../Framework/Scripts/Managers/UIComponent';
const { ccclass, property } = _decorator;

//登录命令号
const CmdLogin = {
    LoginReq:7001,         //登录
}

//登录服务消息处理
@ccclass('GameLoadingMsg')
export class GameLoadingMsg extends UIComponent {
    net: any;
    url: string;
    start() {
        this.InitUI();
        this.InitData();

        this.url = CocosUtils.getUrlByIdAndPort( NetConfig.ip, NetConfig.port);

        this.net = new globalThis.gameMgr.WsMgr();
        this.net.connectServer(this.url);
    }

    update(deltaTime: number) {
        // console.log('========GameLoadingMsg==========',this.net.state);
        if(this.net.state === State.Invalid) {
            return;
        }
        if(this.net.state === State.Disconnected) {
            console.log('=====登录服务重新连接==========')
            this.net.connectServer( this.url);
        }
    }

    protected onDestroy(): void {
        this.unRegisterEvent();
        globalThis.gameMgr._GameLoadingMsg = null;
        delete globalThis.gameMgr._GameLoadingMsg;
    }

    private InitUI(){
        this.registerEvent();       
    }

    private InitData(){
        globalThis.gameMgr._GameLoadingMsg = this;
    }

    private registerEvent(){
        globalThis.gameMgr._eventTarget.on(WSConnectedEvent,this.onConnectLoginServer,this);
        globalThis.gameMgr._eventTarget.on(WSRecvDataEvent,this.onRevLoginData,this);
    }

    private unRegisterEvent(){
        globalThis.gameMgr._eventTarget.off(WSConnectedEvent,this.onConnectLoginServer,this);
        globalThis.gameMgr._eventTarget.on(WSRecvDataEvent,this.onRevLoginData,this);
    }

    //登录服务网络连接成功
    private onConnectLoginServer(event,data){
        console.log('=======onConnectLoginServer===========');
        //加载大厅资源
        ResManager.inst.loadDirAssetboundle([HallPkg],(now: number, total: number)=>{
            var pre = (now / total);
            console.log("======loadHallRes pre========",pre);
            globalThis.gameMgr._eventTarget.emit(EventMsgKes.loading,pre);
        },()=>{
            console.log("======loadHallRes End========")
            globalThis.gameMgr._eventTarget.emit(EventMsgKes.loadingEnd,"");
        })
    }

    //发送JSON数据
    private _sendJson(type: number, data: any){
        console.log('=======_sendJson======',type,data);
        this.net.sendJsonData(type,data);
    }

    /**
    * 发送登录1
    * @param uid  
    * @param name 名字
    * @param avator 头像
    */
    public LoginRes(uid: string, name: string = GameData.inst.defaultName, avator: string = GameData.inst.defaultLogo): void {
        let req:ILoginReq = {
            userOpId: uid,
            name: name,
            avator: avator,
            token:globalThis.token
        }
        console.log('=========LoginRes=======',req);
        this._sendJson(CmdLogin.LoginReq, req);
    }

    //收到登录服务数据
    private onRevLoginData(binaryData){
        console.log('=======onRevLoginData===========',binaryData);
        let msg = JSON.parse(binaryData);
        let ctype = msg.type;
        let data = msg.data;
        this._onMsg(ctype,data);
    }

    private _onMsg(ctype: number, buf:any){
        console.log('=====MsgDataLogin==onMsg========',ctype);
        switch (ctype) {
            case CmdLogin.LoginReq:
                this.onMsgLoginRes(buf);
                break;
        
            default:
                break;
        }
    }

    // 登录协议返回ok
    private onMsgLoginRes(data: IloginRes): void {
        // let data = decodeLoginBackRes(buffer);
        console.log('onMsgLoginRes = ', data);
        //保存用户数据
        if (data.userInfo) {
            GameData.inst.setUserInfo(data.userInfo);
        }
        if (data.hallNet) {
            GameData.inst.hallNetCfg = data.hallNet;
        }
        //如果分服务需要 链接大厅服务 
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgLoginRes, data);
    }
}


